package com.woniu.utils;

import cn.hutool.core.util.ObjectUtil;
import com.woniu.constants.ErrorConstants;
import com.woniu.constants.RedisConstants;
import com.woniu.enums.ServiceExceptionEnum;
import com.woniu.exception.MyErrorException;
import com.woniu.exception.ServiceException;
import com.woniu.vo.TokenUserMesVo;
import com.woniu.vo.TokenVO;
import com.woniu.vo.UserVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;

/**
 * Token工具类
 **/
@Component
public class TokenUtil {

    @Autowired
    private RedisUtil redisUtil;


    //Token解析
    public TokenUserMesVo analysisToken()
    {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        //获取token
        String token = request.getHeader("Token");
        if (StringUtils.isEmpty(token)){
            throw new ServiceException(ServiceExceptionEnum.SYS_UNAUTHORIZED);
        }
        token = token.replaceAll("\"","");
        //获取加密密钥
        String ipAddress = IpUtil.getIpAddress(request);
        String userAgent = BrowserUtil.getUserAgent(request);
        //对token进行解密
        String decrypt = AesUtil.decrypt(token, ipAddress + userAgent);

        if (decrypt == null){
            throw new ServiceException(ServiceExceptionEnum.SYS_UNAUTHORIZED);
        }

        UserVO userVO = redisUtil.getUser(decrypt);
        if (ObjectUtils.isEmpty(userVO)) {
            throw new ServiceException(ServiceExceptionEnum.SYS_UNAUTHORIZED);
        }
        //获取用户名和id
        return ConverterUtil.convert(userVO, TokenUserMesVo.class);

    }

    public String getUserId(){
        TokenUserMesVo tokenUserMesVo = analysisToken();

        if (ObjectUtil.isEmpty(tokenUserMesVo)){
            throw new MyErrorException(ErrorConstants.USER_IS_NULL);
        }

        String userId = tokenUserMesVo.getUserId();

        //String userId = "b068c657-5b5a-40f1-8c52-8ca1d66efe96";

        if (StringUtils.isEmpty(userId)){
            throw new MyErrorException(ErrorConstants.USER_IS_NULL);
        }

        return userId;

    }

    /**
     * 获取token
     */
    public static String getToken(String key) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader("key");
        if (token == null) {
            token = request.getParameter(key);
        }
        if (token == null || token.length() == 0) {
            return null;
        }
        return token;
    }

    /**
     * 创建令牌
     *
     * @param tokenVO
     * @return 令牌
     */
    public String createToken(TokenVO tokenVO) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = RedisConstants.USER_TOKEN_REDIS_KEY_PREFIX + UUID.randomUUID().toString().replace("-", "");
        String ipAddress = IpUtil.getIpAddress(request);
        String userAgent = BrowserUtil.getUserAgent(request);
        String reToken = AesUtil.encrypt(token, ipAddress + userAgent);
        tokenVO.setToken(reToken);
        //测试对接先调整过期为720小时
        redisUtil.setOpsForValue(token, tokenVO, 720L, DefaultTimeUtil.TOKEN_UNIT);
        return reToken;
    }


}
